const express = require('express');
const path = require('path');
const app = express();
const ejs = require('ejs');
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const compression = require('compression');
const fs = require("fs");
const _ = require("lodash");


let users = [];

app.set('views', path.join(__dirname, 'views'));
app.engine('html',ejs.__express);
app.set('view engine', 'html');

app.use(compression());

app.use('/static',express.static('static'));


app.get('/', (req, res, next)=> {
    res.render('audition');
});
app.get('/admin', (req, res, next)=> {
    res.render('admin',{
        test: "test",
        users
    });
});


var admin = io.of('/admin')

admin.on('connection',socket=>{

    socket.on('getCode',(data)=>{
        io.emit('sendCode',data);
    })
})

io.on('connection', socket => {
    socket.on('connected',(name)=>{
        users.push(name)
        users = _.uniq(users).filter(a=>{
            return !isEmpty(a);
        });
        console.log(name + " 上线了");
    })
    socket.on('message',(data)=>{
        admin.emit('onCodeChange',data);
        if(data.type==="save"){
            fs.writeFile(path.join(__dirname, 'files')+"\\"+data.name+'.txt',data.msg,function (err){
                if(err){
                    console.log(err);
                }
            });
        }
    })

});






function isEmpty(t){
    return !t || (t = t.toString(),
        t = t.replace(/\ +/g, ""),
        t = t.replace(/[ ]/g, ""),
    (t = t.replace(/[\r\n]/g, "")) === "")
}



server.listen(3000);